package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.dto.DevicePageQueryDto;
import com.zzyl.entity.Device;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.DeviceLocationTypeEnum;
import com.zzyl.enums.DevicePhysicalLocationTypeEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.DeviceVo;
import com.zzyl.vo.ProductVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description DeviceServiceImpl
 * @Author luohai
 * @Date 2024-10-30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceServiceImpl implements DeviceService {

    private final AliIoTConfigProperties aliIoTConfigProperties;

    private final Client client;

    private final StringRedisTemplate redisTemplate;

    private final DeviceMapper deviceMapper;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //调用查询IOT所有产品列表：QueryProductList
        //1.构建查询产品列表请求对象
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2.client执行查询产品列表接口调用，返回响应对象
        QueryProductListResponse response = null;
        //3.处理远程接口调用异常，结束应用程序
        try {
             response = client.queryProductList(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }
        //4.获取响应体success判断是否调用成功，失败抛出异常，结束程序
        if (!response.getBody().getSuccess()) {
            log.error("同步IOT所有产品列表数据发生错误：{}",response.getBody().getErrorMessage());
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }
        //5.获取响应体 body.data.list.productInfo集合
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        //6.将productInfo集合转换为List<ProductVo>
        List<ProductVo> productVos = BeanUtil.copyToList(productInfo, ProductVo.class);
        //7.写入缓存
        redisTemplate.opsForValue().set(Constants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(productVos));
    }

    /**
     * 查询所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从缓存中获得数据（json字符串）
        String json = redisTemplate.opsForValue().get(Constants.ALL_PRODUCT_KEY);
        //如果数据为空，则返回空
        if (StrUtil.isEmpty(json)){
            return null;
        }
        //将json字符串转成ProductVo集合
        List<ProductVo> list = JSONUtil.toList(json, ProductVo.class);
        //返回数据
        return list;
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.查询数据库注册的设备英文名是否重复
        Long count=deviceMapper.findRegisterByName(deviceDto.getDeviceName());
        //根据设备英文名查询设备对应数量
        //数量大于0，说明已存在，抛出异常结束程序
        if (count>0){
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //2.远程调用IOT注册设备RegisterDevice接口，并且获取生成的设备id
        //从deviceDto中获取注册设备请求对象
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        //注册设备请求对象封装IotInstanceId属性
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //远程调用注册设备接口获取返回RegisterDeviceResponse对象
        RegisterDeviceResponse response;
        //捕获远程调用可能发生的异常,抛出友好提示异常
        try {
            response=client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //获取RegisterDeviceResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常
        if (!response.getBody().getSuccess()){
            log.error("注册失败，失败原因是{}",response.getBody().getErrorMessage());
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //接口调用成功，获取生成的设备id（响应体data.IotId），封装到deviceDto
        deviceDto.setIotId(response.getBody().getData().getIotId());
        //3.deviceDto转换为device对象
        Device device = BeanUtil.toBean(deviceDto,Device.class);
        //4.补全产品的名字，远程调用查询产品QueryProduct接口
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        //构建查询产品请求对象，封装属性ProductKey和IotInstanceId
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(device.getProductKey());
        //远程调用注册设备接口获取返回QueryProductResponse对象
        QueryProductResponse queryProductResponse;
        //捕获远程调用可能发生的异常,抛出友好提示异常
        try {
            queryProductResponse =client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //获取QueryProductResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常
        if (!queryProductResponse.getBody().getSuccess()) {
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //接口调用成功，获取产品名字（响应体data.ProductName），封装到device
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        //5.判断设备位置绑定类型是否为随身设备，如果是设置物理班绑定类型（physicalLocationType）为-1
        if (DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal().equals(device.getLocationType())){
            device.setPhysicalLocationType(DevicePhysicalLocationTypeEnum.ELDER.getOrdinal());
        }
        //6.将设备保存到数据库
        //补全是否包含门禁，默认设置为0
        device.setPhysicalLocationType(0);
        try {
            //调用mapper保存
            deviceMapper.insertSelective(device);
        } catch (Exception e) {
            //捕获异常，远程调用删除IOT设备接口（DeleteDevice）
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            //构建查删除IOT设备请求对象，封装属性IotInstanceId和IotId
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setIotId(device.getIotId());
            //远程调用删除设备接口
            DeleteDeviceResponse deleteDeviceResponse = null;
            try {
                deleteDeviceResponse=client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                //捕获删除设备远程接口调用发生异常（如果其企业中删除失败，会记录日志，通知管理员（邮件或手机短信））
                log.error("注册设备失败，失败原因：{}","删除iot的设备失败");
            }
            //获取QDeleteDeviceResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常（如果其企业中删除失败，会记录日志，通知管理员（邮件或手机短信））
            if (!deleteDeviceResponse.getBody().getSuccess()){
                log.error("注册设备失败，失败原因：{}","删除iot的设备失败");
            }
            //抛出异常结束，提示友好信息
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
    }

    /**
     * 分页查询设备数据
     * @param devicePageQueryDto
     * @return
     */
    @Override
    public PageResponse<DeviceVo> pageQueryDevice(DevicePageQueryDto devicePageQueryDto) {
        PageHelper.startPage(devicePageQueryDto.getPageNum(),devicePageQueryDto.getPageSize());
        Page<DeviceVo> page=deviceMapper.pageQueryDevice(devicePageQueryDto);
        PageResponse<DeviceVo> objectPageResponse = new PageResponse<>();
        objectPageResponse.setRecords(page);
        return objectPageResponse;
    }

    /**
     * 查询设备详细数据
     * @param request
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(QueryDeviceDetailRequest request) {
        //根据IotId查询DeviceVo对象
        DeviceVo deviceVo = deviceMapper.findDeviceByIotId(request.getIotId());
        if (ObjectUtil.isEmpty(deviceVo)){
            throw new RuntimeException("查询数据为空");
        }
        //封装IotInstanceId属性
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //调用远程iot接口
        QueryDeviceDetailResponse response = null;
        try {
            response=client.queryDeviceDetail(request);
        } catch (Exception e) {
            log.error("远程查询iot信息失败，失败原因为：{}",e.getMessage());
        }
        //如果远程接口调用失败就打印失败日志
        if (!response.getBody().getSuccess()){
            log.error("远程查询iot信息失败，失败原因为：{}",response.getBody().getErrorMessage());
        }
        //如果远程接口调用成功就合并数据到deviceVo
        if (response.getBody().getSuccess()){
            BeanUtil.copyProperties(response.getBody().getData(),deviceVo);
        }
        //返回数据deviceVo
        return deviceVo;
    }

    /**
     * 查询指定设备的物模型运行状态
     * @param request
     * @return
     */
    @Override
    public QueryDevicePropertyStatusResponse QueryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response=null;
        try {
            response=client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException("查询物模型状态失败");
        }

        if (!response.getBody().getSuccess()){
            throw new RuntimeException("查询物模型状态失败");
        }
        return response;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     * @param request
     * @return
     */
    @Override
    public QueryThingModelPublishedResponse QueryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response=null;
        try {
            response=client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException("查询物模型功能失败");
        }

        if (!response.getBody().getSuccess()){
            throw new RuntimeException("查询物模型功能失败");
        }
        return response;
    }

    /**
     * 修改设备备注名称
     * @param deviceDto
     * @return
     */
    //BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        RegisterDeviceRequest requestValue = deviceDto.getRegisterDeviceRequest();
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> infoList=new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo bud = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        bud.setNickname(requestValue.getNickname());
        bud.setDeviceName(requestValue.getDeviceName());
        bud.setProductKey(requestValue.getProductKey());
        infoList.add(bud);
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setDeviceNicknameInfo(infoList);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        BatchUpdateDeviceNicknameResponse response=null;
        try {
            response=client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException("批量修改设备异常");
        }

        if (!response.getBody().getSuccess()){
            throw new RuntimeException("批量修改设备异常");
        }

        Device device = BeanUtil.toBean(deviceDto, Device.class);
        deviceMapper.updateByPrimaryKeySelective(device);
    }

    /**
     * 删除设备
     * @param request
     * @return
     */
    @Override
    public void deleteDevice(DeleteDeviceRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response=null;
        try {
            response=client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("删除设备失败");
        }
        if (!response.getBody().getSuccess()){
            throw new RuntimeException("删除设备失败");
        }
        deviceMapper.deleteByIotId(request.getIotId());
    }
}
